import { Input, input, EventTouch, v2, Vec2, math, log, screen } from 'cc';
import { Observable, Observer, filter } from "rxjs";

export function TouchStart() {
    return new Observable((observer: Observer<EventTouch>) => {
        const onTouchStart = (eventTouch: EventTouch) => {
            observer.next(eventTouch);
        };
        input.on(Input.EventType.TOUCH_START, onTouchStart, this);
        return () => {
            input.off(Input.EventType.TOUCH_START, onTouchStart, this);
        }
    });
}

export function TouchEnd() {
    return new Observable((observer: Observer<EventTouch>) => {
        const onTouchEnd = (eventTouch: EventTouch) => {
            observer.next(eventTouch);
        };
        const onTouchCancel = (eventTouch: EventTouch) => {
            observer.next(eventTouch);
        }
        input.on(Input.EventType.TOUCH_END, onTouchEnd, this);
        input.on(Input.EventType.TOUCH_CANCEL, onTouchCancel, this);
        return () => {
            input.off(Input.EventType.TOUCH_END, onTouchEnd, this);
            input.off(Input.EventType.TOUCH_CANCEL, onTouchCancel, this);
        }
    });
}

export function TouchMove() {
    return new Observable((observer: Observer<EventTouch>) => {
        const onTouchMove = (eventTouch: EventTouch) => observer.next(eventTouch);
        input.on(Input.EventType.TOUCH_MOVE, onTouchMove, this);
        return () => {
            input.off(Input.EventType.TOUCH_MOVE, onTouchMove, this);
        }
    });
}

const _v0 = v2();
const _v1 = v2();
const tolerate = 4;

export function Click() {
    return TouchEnd().pipe(filter(eventTouch => {
        eventTouch.getStartLocation(_v0);
        eventTouch.getLocation(_v1);
        return Vec2.distance(_v0, _v1) < tolerate * screen.devicePixelRatio;
    }));
}